<!-- 房源搬家 -->
<template>
  <div
    class="app-container"
    v-loading.fullscreen="loading"
    element-loading-text="正在房源搬家中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <com-title-item title="注意事项">
      <div class="body fs-md">
        <div>
          1、本功能支持复制居客网、同城网等（支持二手房和出租房，不支持新房。复制所需要的房源详情网址到输入框进行房源搬家。如图提示）
        </div>
        <div>
          <img src="@/assets/images/url.png" alt srcset />
        </div>
        <div>2、复制成功房源后请注意修改相关信息。</div>
        <div>3、由于某些房源信息是公司性质的定制模板，房源描述会不完整，敬请谅解。</div>
        <div>
          4、注意：请将本功能用于合法用途，
          <span class="text-red">如引起侵权或违规，属于您的个人行为，本站不承担任何责任。</span>
        </div>
      </div>
    </com-title-item>

    <com-title-item title="房源搬家地址">
      <div class="imgs">
        <img
          @click="open('https://shanghai.anjuke.com/?pi=PZ-baidu-pc-all-biaoti')"
          class="icon item"
          src="@/assets/images/ajk.png"
          alt
          srcset
        />
        <!-- <img class="item" @click="open('https://sh.ke.com/')" src="@/assets/images/bk.png" alt srcset /> -->
        <img class="item" @click="open('https://sh.58.com/ershoufang/')" src="@/assets/images/58.png" alt srcset />
        <!-- <img class="item" @click="open('https://sh.lianjia.com/')" src="@/assets/images/lj.png" alt srcset /> -->
        <!-- <img class="item" @click="open('https://www.baidu.com/')" src="@/assets/images/bd.png" alt srcset /> -->
      </div>
    </com-title-item>

    <com-title-item title="房源搬家">
      <div class="move">
        <div class="item" v-for="(item, index) in houseUrlList" :key="item.id">
          <el-row :gutter="20" :index="index" class="d-flex ai-center">
            <el-col :span="12">
              <el-input placeholder="粘贴房源地址" v-model="item.url"></el-input>
            </el-col>
            <el-col :span="12" class="d-flex ai-center">
              <i class="el-icon-circle-plus-outline fs-icon" v-if="isButtonAdd(index)" @click="handleAdd"></i>
              <i class="el-icon-remove-outline fs-icon icon-red" v-else @click="handleCancel(index)"></i>
              <el-button
                v-if="isButtonAdd(index)"
                type="primary"
                :disabled="isDisable"
                @click="handleComfirm"
                style="margin-left: 20px"
                >确定搬家</el-button
              >
            </el-col>
          </el-row>
        </div>
        <div class="vr d-flex ai-center fs-l">
          <div class="title">下载VR房源</div>
          <div class="select">
            <el-radio v-model="radio" label="1">是</el-radio>
            <el-radio v-model="radio" label="2">否</el-radio>
          </div>
          <div class="text-gray"></div>
        </div>
        <div class="fs-md text-gray-light" style="margin-top: 10px;">
          备注：当房源为VR房源时才可以进行VR下载，VR预计5分钟后下载完成
        </div>
        <div class="comfirm d-flex ai-center jc-center">
          <!-- <el-button type="info" @click="$router.replace('/')">取消</el-button> -->
        </div>
      </div>
    </com-title-item>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { menuHandler } from "@/handler/menuHandler";
import { HOUSE_MOVE, VR_COMPOUND_ADD } from "@/config/menuId";
import comTitleItem from "./com/com-title-item";
import {
  getMemberPower,
  movingHouse,
} from "@/api/user";
import { debounce, throttle, unique } from "@/utils/utilsNew";

let count = 0;
export default {
  data() {
    return {
      loading: false,
      houseUrlList: [this.createHouseUrlItem()],
      radio: "1",
    };
  },
  components: {
    comTitleItem,
  },
  computed: {
    ...mapGetters(["sessionUser"]),
    isButtonAdd() {
      return (index) => index == 0;
    },
    isDisable() {
      return this.houseUrlList.every((v) => !v.url) || this.loading;
    },
  },
  created() {
    this.handleComfirm = throttle(this.handleComfirm.bind(this), 2000);
  },
  mounted() {
    // gio('track',  constant.MY_PAGE_VIEW)
  },
  methods: {
    async handleAdd() {
      if (this.houseUrlList.length >= 5) return this.$message.error("批次搬家最多5套");

      try {
        await menuHandler.call(this, HOUSE_MOVE, 0);
        this.houseUrlList.push(this.createHouseUrlItem());
        if (this.houseUrlList.length > 5)  {
          this.houseUrlList = this.houseUrlList.slice(0, 5)
        }
      } catch (error) {}
    },

    handleCancel(index) {
      this.houseUrlList.splice(index, 1);
    },
    createHouseUrlItem() {
      return { id: ++count, url: "" };
    },

    async handleComfirm() {
      let arr = this.houseUrlList
        .map((v) => {
          let i = v.url.indexOf("http");
          return i > -1 ? v.url.slice(i) : "";
        })
        .filter((v) => !!v);
      arr = unique(arr);

      const result = arr.map((item) => ({
        url: item,
        vrFlag: this.radio == "1",
      }));

      this.loading = true;

      try {
        // 搬家校验
        await menuHandler.call(this, HOUSE_MOVE, result.length);

        // vr是否下载判断
        if (this.radio == "1") {
          await menuHandler.call(this, VR_COMPOUND_ADD, result.length);
          const content = await this.fetchPickOutHouse(result);

          // 使用采集vr次数
          getMemberPower({
            menuId: VR_COMPOUND_ADD,
            agentId: this.sessionUser.id,
            num: result.length,
          });

          this.$message.info(`vr预计${content.length * 5}分钟后下载完成`);
        } else {
          await this.fetchPickOutHouse(result);
        }

        // 使用搬家次数
        getMemberPower({
          menuId: HOUSE_MOVE,
          agentId: this.sessionUser.id,
          num: result.length,
        });
      } catch (error) {
        console.log(error);
      }
      this.loading = false;
    },

    fetchPickOutHouse(arr) {
      return new Promise((resolve, reject) => {
        movingHouse(arr).then((data) => {
          if (data.isSuccess) {
            resolve(data.content);

            this.$messageBox
              .confirm(`本次共提交${arr.length}条搬家任务，大约需要${arr.length * 2}分钟`, {
                confirmButtonText: "继续搬家",
                cancelButtonText: "查看搬家日志",
              })
              .then(() => {
                count = 0;
                this.houseUrlList = [this.createHouseUrlItem()];
              })
              .catch((err) => {
                this.$nextTick(() => {
                  this.$router.push({ name: "moveLog" });
                });
              });
          } else {
            this.$message.error("非常抱歉：本次搬家失败，请试试其他链接。");
            reject();
          }
        });
      });
    },

    open(url) {
      window.open(url);
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #f6f6f6;
  .fs-icon {
    cursor: pointer;
    font-size: 28px;
    color: #409eff;

    &.icon-red {
      color: #f56c6c;
    }
  }
  .body {
    background-color: #f6f6f6;
    padding: 18px 28px;
    margin-top: 12px;
    line-height: 26px;
  }
  .imgs {
    margin-top: 14px;
    .item {
      margin-right: 20px;
      border-radius: 4px;
      overflow: hidden;
      width: 120px;
      height: 56px;
    }
  }
  .move {
    margin-top: 14px;
    .item {
      margin-bottom: 10px;
    }
    .vr {
      margin-top: 20px;
      .title {
        margin-right: 10px;
      }
      .select {
        margin-right: 30px;
      }
    }
    .comfirm {
      margin-top: 60px;
    }
  }
}
</style>
